# common definition
require "fileutils"
require "dbm"

LOCAL_TIME_STAMP    = 1
SESSION_ID          = 2
SESSION_START_TIME  = 3
CLIENT_IP           = 4
SERVER_IP           = 5
L4_PROTO            = 6
CLIENT_PORT         = 7
SERVER_PORT         = 8
CLIENT_PAYLOAD_HEX  = 9
SERVER_PAYLOAD_HEX  = 10
PROTOCOL            = 11
CLIENT_PAYLOAD      = 12
SERVER_PAYLOAD      = 13



#
# File directories
#
DB_FILES = "./db_files"

#
#
#

module Common
  def self.file_exist?(dir, file_name)
    # db_list = Dir.entries DB_FILES
    db_list = Dir.entries dir
    db_list.each do |db_name|
      if db_name.include?(file_name)
        return true
      end
    end
    false
  end

  def self.db_exist?(file_name)
    file_exist?(DB_FILES, file_name)
  end

  def self.move_file(file_name, dir_name)
    if !File.exist?(dir_name)
      FileUtils.mkdir dir_name
    end

    if !(File.exist?(file_name))
      puts "file doesn't exist:" + file_name 
      return
    end

    if dir_name[-1,1] != "/"
      dir_name = dir_name + "/"
    end

    FileUtils.mv file_name, dir_name + file_name
  end

  def self.get_all_files(dir)
    # file_list = Dir.entries dir
    # file_list.delete_at 0 # to delete "."
    # file_list.delete_at 0 # to delete ".."
    # file_list
    rtn = []
    file_list = Dir.entries dir

    file_list.each do |file_name|
      unless file_name.start_with? "."
        rtn << file_name
      end
    end

    rtn
  end

  def self.output_hash_to_file(map, file_name)
    file = File.open file_name, 'w'
    map.each do |key,value|
      file.puts "#{key}|#{value}"
    end
    file.close
  end

  def self.extract_domain(url)
    rzt = String.new url
    ipaddress = rzt[ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\:\d{0,6})?/ ]

    if ipaddress
      rzt = ipaddress
    else
      fields = url.split "."
      # if fields.length > 3
      if fields.length >= 3
        # rzt = fields[-3] + "." + fields[-2] + "." + fields[-1]    
        rzt = fields[-2] + "." + fields[-1]    
      end
    end
    rzt.downcase
  end

  def self.check_string(str)
    if !str
      return "NULL"
    elsif str.length == 0
      return "NULL"
    else
      return str.strip
    end
  end


  def self.alternate_file_name(file_name, original_key_word, new_key_word)
    if !(file_name.include? original_key_word)
      raise "original_key_word unfound : #{original_key_word}" 
    end
    new_file_name = String.new file_name
    new_file_name[original_key_word] = new_key_word
    new_file_name
  end
end